//
//  CZQLongViewController.m
//  coachmanage
//
//  Created by 众拳科技 on 2018/3/12.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "CZQLongViewController.h"
#import "CZQLongCollectionViewCell.h"
#import "CZQLongOneCollectionViewCell.h"
#import "AddSideView.h"
#import "CZQLongBtnView.h"
@interface CZQLongViewController () <UICollectionViewDelegate,UICollectionViewDataSource>
{
    
    UICollectionViewFlowLayout *flowLayout;
    
}
@property(nonatomic,strong)NSMutableDictionary *dict;

@property(nonatomic,strong)UICollectionView * collectionView;

/**
 所有数据
 */
@property(nonatomic,strong)NSMutableArray *dataArrM;



@end

@implementation CZQLongViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"擅长的技能";
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    if (self.resumeModel.FavTags.length > 0) {
        self.seletDataArrM = [NSMutableArray arrayWithArray:[self.resumeModel.FavTags componentsSeparatedByString:@","]];
    }
    
    
    
    [self loadData];
    
    // Do any additional setup after loading the view.
}

-(void)handleData
{
    
    self.dataArrM = [NSMutableArray arrayWithArray:@[@"游泳",@"散步",@"打游戏",@"睡觉",@"足球",@"篮球",@"跑步",@"健身"]];
    
    [self.collectionView reloadData];
    
    
}

-(void)loadData{
    
//    NSUserDefaults *userDetault = [NSUserDefaults standardUserDefaults];
//
//    NSString *userId = [userDetault objectForKey:@"UserID"];
//
//    NSString *url =[NSString stringWithFormat:@"%@/%@",Get_Users,userId];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [HTTPTool GET:Get_Users_FavTagList parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  self.dataArrM = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"Rows"]];
                  
                  
                  
                  [self.collectionView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
//              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma  mark -懒加载
-(NSMutableArray *)dataArrM
{
    if (!_dataArrM) {
        _dataArrM = [NSMutableArray array];
    }
    
    return _dataArrM;
    
}

-(NSMutableArray *)seletDataArrM
{
    if (!_seletDataArrM) {
        _seletDataArrM = [NSMutableArray array];
    }
    
    return _seletDataArrM;
    
}


-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        flowLayout= [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//滚动方向
        flowLayout.minimumLineSpacing = 5;//行间距(最小值)
        flowLayout.minimumInteritemSpacing = 5;//item间距(最小值)
        
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 30, 5, 30);//设置section的边距
        
        //item的大小
        flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 20);
        flowLayout.footerReferenceSize = CGSizeMake(self.view.frame.size.width, 20);
        
        UICollectionView *collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout ];
        //注册cell
        
        [collection registerNib:[UINib nibWithNibName:@"CZQLongOneCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CZQLongOneCollectionViewCell"];
        
        [collection registerNib:[UINib nibWithNibName:@"CZQLongCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CZQLongCollectionViewCell"];
        
        
        //注册段头
        [collection registerNib:[UINib nibWithNibName:@"DHHeadCollecView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head1"];
        //注册段尾
        [collection registerNib:[UINib nibWithNibName:@"DHFooterReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
        [collection registerNib:[UINib nibWithNibName:@"DHFooterReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer1"];
        collection.backgroundColor = [UIColor whiteColor];
        //设置代理
        collection.delegate = self;
        collection.dataSource = self;
        [self.view addSubview:collection];
        
        [collection mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(self.view);
            
        }];
        
        _collectionView = collection;
        
    }
    return _collectionView;
}

#pragma mark ---- UICollectionViewDelegate && UICollectionViewDatasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (section == 0) {

        return 1;
        
    }
    
    return self.dataArrM.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        CZQLongOneCollectionViewCell *oneCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CZQLongOneCollectionViewCell" forIndexPath:indexPath];
        
        [oneCell.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        for (int i = 0 ; i < self.seletDataArrM.count; i ++ ) {
            
            CZQLongBtnView *view = [[CZQLongBtnView alloc]initWithFrame:CGRectMake(10 + 120 *i, 5, 100, 50)];
            
            view.tag = 100 + i;
            
            //删除
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeLong:)];
            
            [view addGestureRecognizer:tap];
            
            
            view.longLable.text = self.seletDataArrM[i];
            
            [oneCell.scrollView addSubview:view];
            
            
            
        }
        
        oneCell.scrollView.contentSize = CGSizeMake(120 * self.seletDataArrM.count, 0);
        
        [oneCell.eidtBtn addTarget:self action:@selector(add)];
        
        return oneCell;
        
    }
    
    
    CZQLongCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CZQLongCollectionViewCell" forIndexPath:indexPath];
    
    BOOL isSelet = NO;
    
    for (NSString *str in self.seletDataArrM) {
        
        if ([self.dataArrM[indexPath.row] isEqualToString:str]) {
            
            isSelet = YES;
            
        }
        
    }
    
    [cell.longBtn setTitle:self.dataArrM[indexPath.row]];
    
 
    if (isSelet == YES) {
        
        cell.backgroundColor = ButtonBackGroundColor;
        
        cell.layer.borderWidth = 0;
    }else
    {
        cell.layer.borderWidth = 1.0f;
        
        cell.layer.borderColor = CSColorFromRGB(0xdbdbdb).CGColor;
        
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    
    
    
    return cell;
}

//设置cell的偏移量
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsZero;
    }
    
    return UIEdgeInsetsMake(10, 20, 10, 20);
}

//设置cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    __block NSInteger countItem;
    __block CGFloat w;
    dispatch_block_t block = ^{
        NSLog(@"%f",flowLayout.sectionInset.left);
        CGFloat width = self.view.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right;
        w= floorf((width - (countItem - 1) * flowLayout.minimumInteritemSpacing) / countItem);
    };
    
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, 80);
    }else
    {
        flowLayout.minimumLineSpacing = 5;//行间距(最小值)
        flowLayout.minimumInteritemSpacing = 5;//item间距(最小值)
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);//设置section的边距
        
        countItem = 3;
        block();
        
        
        return CGSizeMake(w, 50);
        
    }
    
    return CGSizeZero;
    
}

//设置段头的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 0);
    }
    return CGSizeMake(kScreenWidth, 20);
}

//设置段尾大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(0, 0);
    }else if (section == 1)
    {
        return CGSizeMake(kScreenWidth, 40);
    }
    return CGSizeMake(kScreenWidth, 30);
}

//指定段头段尾
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    UICollectionReusableView *view = [UICollectionReusableView new];
//
//    view.backgroundColor = BackGroundColor;
//
//    return view;
//
//
//}

//高亮
-(BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//高亮设置YES走这步设置选中高亮颜色
-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    //    cell.college.backgroundColor = bk_click[indexPath.row];
}

//高亮设置YES走这步设置选中非高亮颜色
- (void )collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    //    cell.college.backgroundColor = bk[indexPath.row];
}

//点击cell触发
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CZQLongCollectionViewCell *oneCell = [collectionView cellForItemAtIndexPath:indexPath];
    

    BOOL isSelet = NO;
    
    for (NSString *str in self.seletDataArrM) {
        
        if ([self.dataArrM[indexPath.row] isEqualToString:str]) {
            
            isSelet = YES;
            
        }
        
    }
    
    if (isSelet) {
        
        
        oneCell.layer.borderWidth = 1.0f;
        
        oneCell.layer.borderColor = CSColorFromRGB(0xdbdbdb).CGColor;
        
        oneCell.backgroundColor = [UIColor whiteColor];
        
        [self.seletDataArrM removeObject:self.dataArrM[indexPath.row]];
        
    }else
    {
        
        
        oneCell.backgroundColor = ButtonBackGroundColor;
        
        oneCell.layer.borderWidth = 0;
        
        [self.seletDataArrM addObject:self.dataArrM[indexPath.row]];
        
        
        
    }
    
    
    
    [UIView performWithoutAnimation:^{
        [collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    }];
    
}

//是否允许点击cell
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return YES;
}

#pragma mark -删除擅长
-(void)removeLong:(UITapGestureRecognizer *)tap
{
    CZQLongBtnView *view = tap.view;
    
    [self.seletDataArrM removeObjectAtIndex:view.tag -100];
    
    [UIView performWithoutAnimation:^{
        [self.collectionView reloadData];
    }];
    
}
#pragma mark -添加擅长类型
-(void)add
{
    
    AddSideView *addSideView = [[AddSideView alloc] init];
    
    addSideView.unitTF.hidden = YES;
    
    addSideView.titleLabel.text = @"自定添加标签";
    
    addSideView.dict = self.dict;
    
    __weak __typeof(self) weakSelf = self;
    
    addSideView.commitBlock = ^(NSString *name, NSString *unit) {
        
        //页面显示
//        [weakSelf.dict setObject:unit forKey:name];
        
        if ([self.dataArrM containsObject:name]) {
            
            [MBProgressHUD showText:@"该标签已存在"];
            
            return ;
            
        }
        
        [weakSelf.dataArrM addObject:name];
        
        [weakSelf.collectionView reloadData];
        
        
    };
    
    [addSideView showWithAnimation];
    
}

#pragma mark - 保存

-(void)save
{
    if (self.seletDataArrM.count > 0) {
        self.resumeModel.FavTags = [self.seletDataArrM componentsJoinedByString:@","];
        
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        self.resumeModel.FavTags = @"";
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    if (self.saveBlock) {
        self.saveBlock();
        
    }
    
    //发送一个通知
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"resume" object:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
